<?php

declare (strict_types = 1);

namespace app\admin\controller\admin;

use app\admin\controller\Base;
use think\db\exception\DataNotFoundException;
use think\db\exception\DbException;
use think\db\exception\ModelNotFoundException;
use think\response\Json;
use app\admin\model\admin\Api as ApiModel;

/**
 * 后台API权限控制器
 * Class Api
 */
class Api extends Base
{
    /**
     * 权限列表
     * @return Json
     * @throws DataNotFoundException
     * @throws DbException
     * @throws ModelNotFoundException
     */
    public function list(): Json
    {
        $model = new ApiModel;
        $list = $model->getList($this->request->param());
        return $this->returnSuccess(compact('list'));
    }

    /**
     * 新增权限
     * @return Json
     */
    public function add(): Json
    {
        // 新增记录
        $model = new ApiModel;
        if ($model->add($this->postForm())) {
            return $this->returnSuccess('添加成功');
        }
        return $this->returnError($model->getError() ?: '添加失败');
    }

    /**
     * 编辑权限
     * @return Json
     * @throws DataNotFoundException
     * @throws DbException
     * @throws ModelNotFoundException
     */
    public function edit(): Json
    {
        $postData = $this->postData();
        $apiId = $postData['apiId'];

        // 权限详情
        $model = ApiModel::detail($apiId);
        // 更新记录
        if ($model->edit($this->postForm())) {
            return $this->returnSuccess('更新成功');
        }
        return $this->returnError($model->getError() ?: '更新失败');
    }

    /**
     * 删除权限
     * @return Json
     */
    public function deleted(): Json
    {
        $postData = $this->postData();
        $apiId = $postData['apiId'];
        
        // 权限详情
        $model = ApiModel::detail($apiId);
        if (!$model->remove()) {
            return $this->returnError($model->getError() ?: '删除失败');
        }
        return $this->returnSuccess('删除成功');
    }
}